#!/usr/bin/python3
# coding=UTF-8

import sys
sys.path.append("./")
sys.path.append("../")
sys.dont_write_bytecode=True
from fastapi import APIRouter, Request
from fastapi.templating import Jinja2Templates
from services.enums.general import ENV, OSI


general = APIRouter()

templates = Jinja2Templates(directory="./templates")

# 针对Enum，可以使用dir, vars, getattr的函数组合获取对应的查询Key的值
@general.get("/OSI_Model/{env}/Search", summary="基础学习")
async def get_osi_model_info(env: ENV, short_name: str):
    """
    env: 路径参数, 会体现在API的URL上\n
    short_name: 查询参数\n
    """
    # osi_var_list = [attr for attr in dir(OSI) if not attr.startswith("__") and not callable(getattr(OSI, attr))]
    osi_var_list = vars(OSI).get("_member_names_")
    print(osi_var_list)
    if short_name in osi_var_list:
        return {
            "message": "success",
            "result": {
                "env": env, 
                "value": getattr(OSI, short_name)
            }
        }
    else:
        return {
            "message": "fail",
            "result": "查询参数无效!"
        }
    

@general.post("/request/use", summary="如何使用Request对象")
async def exec_demo(item: Request):
    return {
        "url": item.url._url,
        "content-type": item.headers.get("Content-Type"),
        "ip": item.client.host,
        "ua": item.headers.get("user-agent"),
        "cookie": item.cookies,
    }


@general.get("/jinja2/use", summary="Jinja2学习")
def sync_html_by_template(request: Request):
    return templates.TemplateResponse("demo.html", 
                                      {
                                          "request": request,
                                          "osi": OSI._member_names_                                  
                                    },
                                    )

    

